package com.xuecheng.manage_course.service;

import com.xuecheng.framework.domain.course.CourseBase;
import com.xuecheng.framework.domain.course.Teachplan;
import com.xuecheng.framework.domain.course.TeachplanMedia;
import com.xuecheng.framework.domain.course.ext.TeachplanNode;
import com.xuecheng.framework.exception.ExceptionCast;
import com.xuecheng.framework.model.response.CommonCode;
import com.xuecheng.framework.model.response.ResponseResult;
import com.xuecheng.manage_course.dao.CourseBaseRepository;
import com.xuecheng.manage_course.dao.TeachplanMapper;
import com.xuecheng.manage_course.dao.TeachplanMediaRepository;
import com.xuecheng.manage_course.dao.TeachplanRepository;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

import javax.annotation.Resource;
import java.util.List;
import java.util.Optional;

/**
 * 课程Service
 */
@Service
public class TeachplanService {
    // 课程计划Dao-mybatis
    @Resource
    private TeachplanMapper teachplanMapper;
    // 课程计划Dao-Jpa
    @Resource
    private TeachplanRepository teachplanRepository;
    // 课程Dao-Jpa
    @Resource
    private CourseBaseRepository courseBaseRepository;
    // 课程计划和视频关联Dao
    @Resource
    private TeachplanMediaRepository teachplanMediaRepository;

    /**
     * 根据课程id查询课程计划
     *
     * @param courseId 课程id
     * @return 课程计划
     */
    public TeachplanNode findTeachplanList(String courseId) {
        return teachplanMapper.selectList(courseId);
    }

    /**
     * 添加课程计划
     *
     * @param teachplan 课程实体类
     * @return 响应结果
     */
    @Transactional
    public ResponseResult addTeachplan(Teachplan teachplan) {
        // 检查数据
        if (teachplan == null ||
                StringUtils.isEmpty(teachplan.getCourseid()) ||
                StringUtils.isEmpty(teachplan.getPname())) {
            ExceptionCast.cast(CommonCode.INVALID_JSON_PARAMETER);
        }
        // 获取课程id
        String courseid = teachplan.getCourseid();
        // 获取父级id,如果父级id是空,就说明是往根节点添加
        String parentid = teachplan.getParentid();
        if (StringUtils.isEmpty(parentid)) {
            parentid = this.getTeachplanRoot(courseid);
        }
        // 新节点
        Teachplan teachplanNew = new Teachplan();
        // 将页面提交的信息拷贝到新创建出来的节点
        BeanUtils.copyProperties(teachplan, teachplanNew);
        teachplanNew.setCourseid(courseid);
        teachplanNew.setParentid(parentid);
        // 根据parentid查找当前所属的等级
        Optional<Teachplan> optional = teachplanRepository.findById(parentid);
        Teachplan temp = optional.get();
        String grade = temp.getGrade();
        if (grade.equals("1")) {
            teachplanNew.setGrade("2"); // 级别,根据父节点添加
        } else if (grade.equals("2")) {
            teachplanNew.setGrade("3"); // 级别,根据父节点添加
        }
        // 保存新的节点
        teachplanRepository.save(teachplanNew);
        return new ResponseResult(CommonCode.SUCCESS);
    }


    /**
     * 根据课程id查询顶级节点, 如果没有顶级节点,讲被创建
     *
     * @param courseId 课程id
     * @return 课程id
     */
    private String getTeachplanRoot(String courseId) {
        // 添加课程计划之前要先查询课程信息,判断是否有这个课程
        Optional<CourseBase> optional = courseBaseRepository.findById(courseId);
        if (!optional.isPresent()) {
            return null;
        }
        // 拿到课程信息
        CourseBase courseBase = optional.get();
        // 根据课程id 和顶级节点 查询顶级节点id
        List<Teachplan> teachplanList = teachplanRepository.findByCourseidAndParentid(courseId, "0");
        // 如果没有查询到该课程的顶级节点id,说明该课程没有课程计划 应该创建顶级节点
        if (teachplanList == null || teachplanList.size() <= 0) {
            // 查询不到顶级节点, 添加节点
            Teachplan teachplan = new Teachplan();
            teachplan.setGrade("1");
            teachplan.setParentid("0");
            teachplan.setPname(courseBase.getName());
            teachplan.setCourseid(courseBase.getId());
            teachplan.setStatus("0");
            Teachplan save = teachplanRepository.save(teachplan);
            // 返回刚刚创建的跟节点id
            return save.getId();
        }
        return teachplanList.get(0).getId();
    }

    /**
     * 保存课程计划和视频关联信息
     *
     * @param teachplanMedia 课程计划和视频关联
     * @return 结果
     */
    public ResponseResult saveMedia(TeachplanMedia teachplanMedia) {
        if (teachplanMedia == null) {
            return new ResponseResult(CommonCode.INVALID_JSON_PARAMETER);
        }
        String teachplanId = teachplanMedia.getTeachplanId();
        String courseId = teachplanMedia.getCourseId();
        // 判断节点和课程id是否合法
        List<Teachplan> byIdAndCourseid = teachplanRepository.findByIdAndCourseid(teachplanId, courseId);
        if (byIdAndCourseid == null || byIdAndCourseid.size() == 0) {
            return new ResponseResult(CommonCode.INVALID_JSON_PARAMETER);
        }
        // 判断是否是3级节点,只有3级节点才能添加视频
        Teachplan teachplan = byIdAndCourseid.get(0);
        if (!teachplan.getGrade().equals("3")) {
            return new ResponseResult(CommonCode.INVALID_JSON_PARAMETER);
        }
        // 处理课程计划关联视频
        Optional<TeachplanMedia> optional = teachplanMediaRepository.findById(teachplanId);
        TeachplanMedia saveTeachplanMedia;
        saveTeachplanMedia = optional.orElseGet(TeachplanMedia::new);
        // 准备保存的数据
        saveTeachplanMedia.setCourseId(teachplan.getCourseid());
        saveTeachplanMedia.setMediaId(teachplanMedia.getMediaId());
        saveTeachplanMedia.setMediaFileOriginalName(teachplanMedia.getMediaFileOriginalName());
        saveTeachplanMedia.setMediaUrl(teachplanMedia.getMediaUrl());
        saveTeachplanMedia.setTeachplanId(teachplanId);
        teachplanMediaRepository.save(saveTeachplanMedia);

        return new ResponseResult(CommonCode.SUCCESS);
    }
}
